import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import { indexHomeRoutes } from './modules/indexHome'
import { personalRoutes } from './modules/personal'
import { clanMainRoutes } from './modules/clanMain'
import { clanTreeRoutes } from './modules/clanTree'
import { clanCultureRoutes } from './modules/clanCulture'
import { clanConcilRoutes } from './modules/clanConcil'
import { clanCelebritiesRoutes } from './modules/clanFamousConcil'
import { loginRouters } from './modules/login'
import { useUserStore } from '@/stores'
import { clanSearchRoutes } from './modules/clanSearch'
import { clanChatRoutes } from './modules/clanChat'

//Layout下的路由
export const rootRoute: RouteRecordRaw = {
  path: '/',
  name: 'Layout',
  component: () => import('@/layout/index.vue'),
  redirect: '/indexHome',
  meta: {
    title: '首页',
  },
  children: [
    ...clanSearchRoutes,
    ...indexHomeRoutes,
    ...personalRoutes,
    ...clanMainRoutes,
    ...clanTreeRoutes,
    ...clanCultureRoutes,
    ...clanConcilRoutes,
    ...clanCelebritiesRoutes,
    ...clanChatRoutes,
  ],
}

//创建路由实例
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [rootRoute, ...loginRouters],
})

//拦截器
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  console.log('userStore.isLogin', userStore.isLogin)
  console.log('to', to, from)
  //如果没有登录，且不是登录页，跳转到登录页,带上redirect，登录后跳转
  if (!userStore.isLogin && to.path !== '/login') {
    next({ path: '/login', query: { redirect: to.fullPath } })
    return
  }
  NProgress.start()
  next()
})
router.afterEach(() => {
  NProgress.done()
})
export default router
